package MLDA_Process;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import Commons.IOUtil;

public class SATM implements Runnable {

    public int P = 1000;
    public int K = 100;

    public double alpha = 0.1;
    public double beta = 0.01;

    public double kAlpha;
    public double vBeta;

    public int M;
    public int V;

    public int niters = 2000;

    public int npw[][]; // P * V
    public int npwSum[]; // P * 1

    public int npk[][];
    public int npkSum[];

    public int nkw[][];
    public int nkwSum[];

    public int d_assigns[][];
    public int z_assigns[][];

    public double eta[][];

    public double epsilon = 0.001;

    public double corpus_size = 0;

    public String inputPath = "";
    public String outputPath = "";

    public List<List<Integer>> docs = new ArrayList<List<Integer>>();
    public HashMap<String, Integer> w2i = new HashMap<String, Integer>();
    public HashMap<Integer, String> i2w = new HashMap<Integer, String>();

    public SATM(int p, int k, int niters, String inputPath, String outputPath) {
        this.P = p;
        this.K = k;
        this.niters = niters;
        this.inputPath = inputPath;
        this.outputPath = outputPath;
    }

    public void loadTxts(String txtPath) {
        BufferedReader reader = IOUtil.getReader(txtPath, "UTF-8");

        String line;
        try {
            line = reader.readLine();
            while (line != null) {
                List<Integer> doc = new ArrayList<Integer>();

                String[] tokens = line.trim().split("\\s+");
                for (String token : tokens) {
                    if (!w2i.containsKey(token)) {
                        w2i.put(token, w2i.size());
                        i2w.put(w2i.get(token), token);
                    }
                    doc.add(w2i.get(token));
                }
                docs.add(doc);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        M = docs.size();
        V = w2i.size();
        return;
    }

    public void init_model() {
        kAlpha = K * alpha;
        vBeta = V * beta;

        eta = new double[M][P];

        npw = new int[V][P];
        npwSum = new int[P];

        npk = new int[P][K];
        npkSum = new int[P];

        nkw = new int[V][K];
        nkwSum = new int[K];

        z_assigns = new int[M][];
        d_assigns = new int[M][];

        for (int m = 0; m != M; m++) {
            int N = docs.get(m).size();
            corpus_size += N;

            z_assigns[m] = new int[N];
            d_assigns[m] = new int[N];
            int d = (int) Math.floor(Math.random() * P);
            for (int n = 0; n != N; n++) {
                int w = docs.get(m).get(n);
                int z = (int) Math.floor(Math.random() * K);

                npw[w][d]++;
                npwSum[d]++;

                npk[d][z]++;
                npkSum[d]++;

                nkw[w][z]++;
                nkwSum[z]++;

                z_assigns[m][n] = z;
                d_assigns[m][n] = d;
            }
        }

        this.update_eta();
    }

    public void update_eta() {
        eta = new double[M][P];

        for (int m = 0; m != M; m++) {
            double norm = 0.0;
            for (int p = 0; p != P; p++) {
                eta[m][p] = (npwSum[p] + 1.0) / (corpus_size + P);
                for (int n = 0; n != docs.get(m).size(); n++) {
                    int w = docs.get(m).get(n);
                    eta[m][p] *= (npw[w][p] + 1.0) / ((double) npwSum[p] + V);
                }
                norm += eta[m][p];
            }
            for (int p = 0; p != P; p++) {
                eta[m][p] /= norm;
            }
        }
    }

    public void sample_d_z(int m, int n) {
        int w = docs.get(m).get(n);
        int d = d_assigns[m][n];
        int z = z_assigns[m][n];

        npk[d][z]--;
        npkSum[d]--;
        nkw[w][z]--;
        nkwSum[z]--;

        npw[w][d]--;
        npwSum[d]--;

        double pTable[][] = new double[P][K];
        double pSum = 0.0;
        for (int p = 0; p != P; p++) {
            if (eta[m][p] < epsilon)
                continue;
            for (int k = 0; k != K; k++) {
                pTable[p][k] = eta[m][p] * (npk[p][k] + alpha) / (npkSum[p] + K * alpha)
                        * (nkw[w][k] + beta) / (nkwSum[k] + V * beta);
                pSum += pTable[p][k];
            }
        }

        double r = Math.random() * pSum;
        pSum = 0.0;
        boolean brk = false;
        for (int p = 0; p != P; p++) {
            if (brk == true)
                break;
            if (eta[m][p] < epsilon)
                continue;
            for (int k = 0; k != K; k++) {
                pSum += pTable[p][k];
                if (r < pSum) {
                    d = p;
                    z = k;
                    brk = true;
                    break;
                }
            }
        }

        npk[d][z]++;
        npkSum[d]++;
        nkw[w][z]++;
        nkwSum[z]++;

        npw[w][d]++;
        npwSum[d]++;

        z_assigns[m][n] = z;
        d_assigns[m][n] = d;
    }

    public void estimate() {
        long start = 0;
        for (int iter = 0; iter != niters; iter++) {
            System.out.println("SATM Iteration " + iter + " ...");
            start = System.currentTimeMillis();
            if (iter % 500 == 0 && iter != 0) {
                try {
                    this.printTopics(outputPath + "/topTopics_" + iter + ".txt", 20);
                    this.saveWordmap(outputPath + "/wordmap_" + iter + ".txt");
                    this.savePhi(outputPath + "/phi_" + iter + ".txt");
                    this.saveAssign(outputPath + "/zassign_" + iter + ".txt");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            for (int m = 0; m != M; m++) {
                for (int n = 0; n != docs.get(m).size(); n++) {
                    sample_d_z(m, n);
                }
            }
            this.update_eta();
            System.out.println("cost time:" + (System.currentTimeMillis() - start));
        }
    }

    public double[][] computePhi() {
        double[][] phi = new double[K][V];
        for (int k = 0; k != K; k++) {
            for (int v = 0; v != V; v++) {
                phi[k][v] = (nkw[v][k] + beta) / (nkwSum[k] + V * beta);
            }
        }
        return phi;
    }

    public ArrayList<List<Entry<String, Double>>> sortedTopicWords(
            double[][] phi, int T) {
        ArrayList<List<Entry<String, Double>>> res = new ArrayList<List<Entry<String, Double>>>();
        for (int k = 0; k != T; k++) {
            HashMap<String, Double> term2weight = new HashMap<String, Double>();
            for (String term : w2i.keySet())
                term2weight.put(term, phi[k][w2i.get(term)]);

            List<Entry<String, Double>> pairs = new ArrayList<Entry<String, Double>>(
                    term2weight.entrySet());
            Collections.sort(pairs, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> o1,
                                   Entry<String, Double> o2) {
                    return (o2.getValue().compareTo(o1.getValue()));
                }
            });
            res.add(pairs);
        }
        return res;
    }

    public void printTopics(String path, int top_n) throws IOException {
        double[][] phi = computePhi();
        BufferedWriter writer = IOUtil.getWriter(path);
        ArrayList<List<Entry<String, Double>>> pairsList = this
                .sortedTopicWords(phi, K);
        for (int k = 0; k != K; k++) {
            writer.write("Topic " + k + ":\n");
            for (int i = 0; i != top_n; i++) {
                writer.write(pairsList.get(k).get(i).getKey() + " "
                        + pairsList.get(k).get(i).getValue() + "\n");
            }
        }
        writer.close();
    }

    public void savePhi(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");

        double[][] phi = computePhi();
        int K = phi.length;
        assert K > 0;
        int V = phi[0].length;

        try {
            for (int k = 0; k != K; k++) {
                for (int v = 0; v != V; v++)
                    writer.append(phi[k][v] + " ");
                writer.append("\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void saveAssign(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");
        try {
            for (int i = 0; i < z_assigns.length; i++) {
                for (int j = 0; j < z_assigns[i].length; j++) {
                    writer.write(docs.get(i).get(j) + ":" + z_assigns[i][j] + " ");
                }
                writer.write("\n");
            }

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }

    public void saveWordmap(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");

        try {
            for (String word : w2i.keySet())
                writer.append(word + "\t" + w2i.get(word) + "\n");

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void printModel() {
        System.out.println("niters:" + this.niters + "\tbeta:" + this.beta + "\talpha:" + this.alpha + "\tk:" + this.K + "\tp:" + this.P + "\tinput:" + this.inputPath + "\toutput:" + this.outputPath);
    }

    public void run() {
        printModel();
        this.loadTxts(inputPath);//
        this.init_model();
        this.estimate();
        try {
            this.printTopics(outputPath + "/topTopics.txt", 20);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.saveWordmap(outputPath + "/wordmap.txt");
        this.savePhi(outputPath + "/phi.txt");
        this.saveAssign(outputPath + "/zassign.txt");
    }

}
